package com.smart.fifteen.annotate.cacheevict;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("com/smart/fifteen/annotate/applicationContext-annotate.xml");
        UserService userService = (UserService) ac.getBean("userServiceCacheEvict");
        System.out.println("first find");
        userService.getUser("1");

        System.out.println("first remove");
        userService.removeUser("1");

        System.out.println("second find");
        userService.getUser("1");

        /*
                first find
                find user
                find user from DB

                first remove
                remove user   //从缓存中移除

                second find
                find user
                find user from DB   //重新从数据库中获取放入缓存
         */

        System.out.println("----------------------------");

        System.out.println("first find");
        userService.getUser("2");
        userService.getUser("3");

        System.out.println("second find");
        userService.getUser("3");

        System.out.println("first remove");
        userService.removeUser2("2");

        System.out.println("third find");
        userService.getUser("3");

        /*
            first find
                find user
                find user from DB
                find user
                find user from DB
            second find
                //从缓存中获取，没有进入find方法
            first remove
                remove user  //从缓存中移除2, 并将缓存清空
            third find
                find user
                find user from DB  //重新从数据库取出3
         */

        System.out.println("--------------------------");

        System.out.println("first find");
        userService.getUser("4");
        userService.getUser("5");

        System.out.println("second find");
        userService.getUser("4");

        System.out.println("first remove");
        try {
            userService.removeUser4("4");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        System.out.println("third find");
        userService.getUser("4");

        System.out.println("second remove");
        userService.removeUser3("4");

        System.out.println("four find");
        userService.getUser("4");

        /*
            first find
                find user 4
                find user from DB 4
                find user 5
                find user from DB 5
            second find
                //从缓存中获取数据
            first remove
                error 4  //缓存没有被删除
            third find
                //从缓存中获取数据
            second remove
                remove3 user 4   //清空缓存
            four find
                find user 4   //重新从数据库获取数据，并放入缓存
                find user from DB 4
         */

    }
}
